package com.jxpanda.infrastructure.crypto.algorithm.encrypt.contract;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.util.Objects;

public interface AsymmetricEncrypt extends Encrypt<KeyPair> {


    default PublicKey getPublicKey() {
        return getKey().getPublic();
    }

    default PrivateKey getPrivateKey() {
        return getKey().getPrivate();
    }

    default Cipher createCipher(int mode) {
        try {
            Cipher cipher = Cipher.getInstance(getAlgorithm());
            if (mode == Cipher.ENCRYPT_MODE) {
                PublicKey publicKey = getPublicKey();
                Objects.requireNonNull(publicKey, "PublicKey must not be null.");
                cipher.init(mode, publicKey);
            } else if (mode == Cipher.DECRYPT_MODE) {
                PrivateKey privateKey = getPrivateKey();
                Objects.requireNonNull(privateKey, "PublicKey must not be null.");
                cipher.init(mode, privateKey);
            }
            return cipher;
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

}
